#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

void printset(const char *ch, sigset_t &set)
{
    std::cout << "pid: " << getpid() << ch;
    for (int i = 31; i >= 1; i--)
    {
        if (sigismember(&set, i))
        {
            std::cout << 1;
        }
        else
        {
            std::cout << 0;
        }
    }
    std::cout << std::endl;
}

void sig2(int sig)
{
    std::cout << "receive signal: " << sig << " pid: " << getpid() << std::endl;
    signal(2, SIG_DFL);
}

void blockandpinding()
{
    // 2号信号重定义
    signal(2, sig2);
    // 2号信号忽略
    // signal(2, SIG_IGN);

    // 建立block表
    sigset_t block, oblock;
    sigemptyset(&block);
    sigemptyset(&oblock);
    printset("block ", block);

    // 屏蔽信号
    for (int i = 31; i >= 1; i--)
    {
        sigaddset(&block, i);
    }
    printset("block ", block);
    int n = sigprocmask(SIG_SETMASK, &block, &oblock);
    // std::cout << "sigprocmask->ret: " << n << std::endl;

    int count = 0;
    while (1)
    {
        // 获取pending
        sigset_t pending;
        int n1 = sigpending(&pending);
        // std::cout << "sigpending->ret: " << n1 << std::endl;

        // 打印pending
        printset("pending ", pending);

        if (count == 10)
        {
            sigprocmask(SIG_SETMASK, &oblock, nullptr);
        }
        ++count;
        std::cout << count << std::endl;
        sleep(1);
    }
}

int main()
{
    // blockandpinding();
    sigset_t block, oblock;
    sigemptyset(&block);
    sigfillset(&oblock);
    printset("block  ", block);
    printset("oblock ", oblock);

    sigaddset(&block, SIGINT);
    sigdelset(&oblock, SIGINT);
    printset("block  ", block);
    printset("oblock ", oblock);

    sigaddset(&block, SIGINT);
    sigdelset(&oblock, SIGINT);
    printset("block  ", block);
    printset("oblock ", oblock);

    return 0;
}
